﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Ebiz.libs;
using System.Collections.Specialized;

namespace Ebiz
{
    public partial class Site : System.Web.UI.MasterPage
    {
        public string txt = "";

        public string strFName = "";
        public string NavBar = "";

        public Dictionary<string, object> SysUserInfo = new Dictionary<string, object>();
        protected void Page_Load(object sender, EventArgs e){

            string UserIP = "";
            string QryString = "";
            string dbName = DBUtilities.GetDBName("devCon");
            Dictionary<string, object> arrUserInfo = new Dictionary<string, object>();
            if (Request.QueryString["cl"] != null &&
                    !(string.IsNullOrEmpty(Request.QueryString["cl"])))
            {
                QryString = "?cl=" + Request.QueryString["cl"];
                if(Session["UserInfo"] == null){
                    //try fetch query string and get userinfo
                    string PageQuery = CryptLib.Base64(Request.QueryString["cl"], CryptMode.DECRYPT);
                    NameValueCollection QueryChunks = HttpUtility.ParseQueryString(PageQuery);

                    string OpenCLNum = "";
                    string OpenToken = "";
                    string OpenUser = "";

                    int ChunksLen = QueryChunks.Count;
                    if (ChunksLen == 4){
                        bool isAuto = Convert.ToBoolean(QueryChunks[3].ToString());
                        if (isAuto == true) {
                            OpenCLNum = QueryChunks[0].ToString();
                            OpenToken = QueryChunks[1].ToString();
                            OpenUser = QueryChunks[2].ToString();
                            
                            string qry = "SELECT UserAccounts.UserName, UserAccounts.PCName, " +
                            "UserAccounts.IDNetwork, UserAccounts.FullName, UserAccounts.Email, " +
                            "UserAccounts.IDRole, mstRole.RoleAlias, mstRole.IDMenu " +
                            "FROM " + dbName + ".dbo.UserAccounts " +
                            "INNER JOIN " + dbName + ".dbo.mstRole ON UserAccounts.IDRole = mstRole.IDRole " +
                            "WHERE (UserAccounts.UserName = @UserName)";
                            SqlConnection cn = new SqlConnection(DBUtilities.strConnection("devCon"));
                            using (cn){
                                try{
                                    cn.Open();
                                    SqlCommand cmd = new SqlCommand(qry, cn);
                                    cmd.Parameters.AddWithValue("@UserName", OpenUser);
                                    SqlDataReader rdr = cmd.ExecuteReader();
                                    if (rdr.HasRows){
                                        if (rdr.Read()){
                                            //Dictionary<string, object> UserInfo = new Dictionary<string, object>();
                                            SysUserInfo["UID"] = rdr.GetValue(0).ToString();
                                            SysUserInfo["PC"] = rdr.GetValue(1).ToString();
                                            SysUserInfo["IDNet"] = rdr.GetValue(2).ToString();
                                            SysUserInfo["FNAME"] = rdr.GetValue(3).ToString();
                                            SysUserInfo["EMAIL"] = rdr.GetValue(4).ToString();
                                            SysUserInfo["IDROLE"] = rdr.GetValue(5).ToString();
                                            SysUserInfo["ROLE"] = rdr.GetValue(6).ToString();
                                            SysUserInfo["IDMENU"] = rdr.GetValue(7).ToString();
                                            SysUserInfo["SSID"] = Session.SessionID.ToString();
                                            SysUserInfo["SSEXP"] = DateTime.Now.Add(TimeSpan.FromMinutes(15)).ToString("ddMMyyHHmm");

                                            Session["UserInfo"] = SysUserInfo;

                                            //Update User Database
                                            UserIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
                                            UpdateLog(SysUserInfo["UID"].ToString(), SysUserInfo["SSID"].ToString(), UserIP, SysUserInfo["FNAME"].ToString(), SysUserInfo["IDMENU"].ToString());

                                        }else{
                                            Session["ErrCode"] = "ES-104";
                                            Response.Redirect("ErrorPage.aspx", true);
                                        }
                                    }else{
                                        Session["ErrCode"] = "ES-104";
                                        Response.Redirect("ErrorPage.aspx", true);
                                    }
                                }catch (Exception ex){
                                    string errMsg = ex.Message;
                                }finally{
                                    if (cn.State == ConnectionState.Open){
                                        cn.Close();
                                    }
                                }
                            }
                        }else{
                            Session["ErrCode"] = "ES-104";
                            Response.Redirect("ErrorPage.aspx", true);
                        }
                    }else{
                        Session["ErrCode"] = "ES-404";
                        Response.Redirect("ErrorPage.aspx", true);
                    }
                }else{
                    arrUserInfo = (Dictionary<string, object>)Session["UserInfo"];
                    if (arrUserInfo["UID"] == null || string.IsNullOrEmpty(arrUserInfo["UID"].ToString())){
                        //Response.Redirect("Default.aspx", true);
                        Session["ErrCode"] = "ES-404";
                        Response.Redirect("ErrorPage.aspx", true);
                    }else{
                        strFName = arrUserInfo["FNAME"].ToString();
                        NavBar = ShowMenu(arrUserInfo["IDMENU"].ToString());
                    }
                }
                txt = QryString;
            }else{
                arrUserInfo = (Dictionary<string, object>)Session["UserInfo"];
                if (arrUserInfo["UID"] == null ||
                    string.IsNullOrEmpty(arrUserInfo["UID"].ToString())){
                    Response.Redirect("Default.aspx", true);
                }else{
                    strFName = arrUserInfo["FNAME"].ToString();
                    NavBar = ShowMenu(arrUserInfo["IDMENU"].ToString());
                }
            }
        }

        protected void Page_Init(object sender, EventArgs e){
            if (Context.Session != null){
                if (Session.IsNewSession){
                    HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                    if (newSessionIdCookie != null){
                        string newSessionIdCookieValue = newSessionIdCookie.Value;
                        if (newSessionIdCookieValue != string.Empty){
                            // This means Session was timed Out and New Session was started
                            Response.Redirect("Logout.aspx");
                        }
                    }
                }
            }
        }

        private void UpdateLog(string UserName, string SSID, string IPAddress, string FullName, string IDMenu) {
            string dbName = DBUtilities.GetDBName("devCon");
            string qry = "UPDATE " + dbName + ".dbo.UserAccounts SET UserAccounts.Token = @Token, " +
                "UserAccounts.LastLog = GetDate(), UserAccounts.LastIP = @LastIP " +
                "WHERE (UserAccounts.UserName = @UserName)";
            SqlConnection cn = new SqlConnection(DBUtilities.strConnection("devCon"));
            using (cn) {
                try {
                    cn.Open();
                    SqlCommand cmd = new SqlCommand(qry, cn);
                    cmd.Parameters.AddWithValue("@Token", SSID);
                    cmd.Parameters.AddWithValue("@LastIP", IPAddress);
                    cmd.Parameters.AddWithValue("@UserName", UserName);
                    if (cmd.ExecuteNonQuery() < 1) {
                        Session["ErrCode"] = "ES-102";
                        Response.Redirect("ErrorPage.aspx", true);
                    }else{
                        strFName = FullName;
                        NavBar = ShowMenu(IDMenu);
                    }
                }catch(Exception ex){
                    string errMsg = ex.Message;
                }finally{
                    if (cn.State == ConnectionState.Open) {
                        cn.Close();
                    }
                }
            }
        }

        protected static string ShowMenu(string IDMenu){
            string result = "";

            string strQuery = "SELECT IDMenu, MenuLevel, MenuSeq, Alias, MenuName, HasChilds, LinkTo " +
                "FROM mstMenu WHERE (IDMenu IN (" + IDMenu + ")) AND (MenuLevel = 1)" +
                "ORDER BY MenuLevel, MenuSeq DESC";

            string strCon = DBUtilities.strConnection("DevCon");
            SqlConnection sqlCon = new SqlConnection(strCon);
            using (sqlCon){
                sqlCon.Open();
                SqlCommand sqlCmd = new SqlCommand(strQuery, sqlCon);
                SqlDataReader sqlReader = sqlCmd.ExecuteReader();
                if (sqlReader.HasRows){
                    string Navs = "<ul>";
                    string MenuID;
                    string MenuLevel;
                    string MenuSeq;
                    string Alias;
                    string MenuName;
                    string HasChilds;
                    string LinkTo;

                    string tmpNavs = "";
                    while (sqlReader.Read()){
                        MenuID = sqlReader.GetValue(0).ToString();
                        MenuLevel = sqlReader.GetValue(1).ToString();
                        MenuSeq = sqlReader.GetValue(2).ToString();
                        Alias = sqlReader.GetValue(3).ToString();
                        MenuName = sqlReader.GetValue(4).ToString();
                        HasChilds = sqlReader.GetValue(5).ToString();
                        LinkTo = sqlReader.GetValue(6).ToString();

                        if (HasChilds == "Y"){
                            string SubNavs = "";
                            string strSubQuery = "SELECT IDMenu, MenuLevel, MenuSeq, Alias, MenuName, LinkTo " +
                                "FROM mstMenu WHERE (IDMenu IN (" + IDMenu + ")) AND (MenuLevel = 2) " +
                                "AND (IDParent = " + MenuID + ") ORDER BY MenuSeq ASC";
                            SqlConnection sqlConSub = new SqlConnection(strCon);
                            using (sqlConSub){
                                sqlConSub.Open();
                                SqlCommand sqlCmdSub = new SqlCommand(strSubQuery, sqlConSub);
                                SqlDataReader sqlReaderSub = sqlCmdSub.ExecuteReader();
                                if (sqlReaderSub.HasRows){
                                    tmpNavs = "<li class='has-sub'><a href='" + LinkTo + "'><span>" + MenuName + "</span></a>";
                                    SubNavs = "<ul>";
                                    string SubMenuName;
                                    string SubLinkTo;

                                    string SubTmpNavs = "";
                                    while (sqlReaderSub.Read()){
                                        SubMenuName = sqlReaderSub.GetValue(4).ToString();
                                        SubLinkTo = sqlReaderSub.GetValue(5).ToString();
                                        SubTmpNavs = "<li><a href='" + SubLinkTo + "'><span>" + SubMenuName + "</span></a></li>\n";

                                        SubNavs += SubTmpNavs;
                                    }
                                    sqlConSub.Close();
									
                                    SubNavs += "</ul>";
                                    tmpNavs += SubNavs + "</li>\n";
                                }else{
                                    tmpNavs = "<li><a href='" + LinkTo + "'><span>" + MenuName + "</span></a></li>\n";
                                }
                            }
                        }else{
                            tmpNavs = "<li><a href='" + LinkTo + "'><span>" + MenuName + "</span></a></li>\n";
                        }

                        Navs += tmpNavs;
                    }
                    sqlCon.Close();

                    Navs += "</ul>";
                    result += Navs;
                }
            }
            return result;
        }
    }
}
